<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------


namespace app\api\controller\v1;

use app\api\controller\Base;
use app\user\model\Collection;
use service\ApiReturn;
use app\goods\model\Goods as GoodsModel;
use app\goods\model\GoodsSku;
use app\goods\model\Cart as CartModel;
use app\goods\model\CartLog;



/**
 * 购物车接口
 * @package app\api\controller\v1
 */
class Cart extends Base
{
    /**
     * 获取购物车列表
     * @edit 晓风<215628355@qq.com>  2021年3月1日13:46:06 优化查询
     */
    public function get_list($data, $user)
    {
        $userid = $user['id'];
        $time = time();
        $list = CartModel::where('user_id', $userid)->order('id desc')->select();
        foreach ($list as &$item) {
            
            $goods = GoodsModel::where("id",$item["goods_id"])
                    ->where("status",1)
                    ->where("is_sale",1)
                    ->where("is_delete",0)
                    ->field("stock,member_price,shop_price,is_spec,name,thumb")
                    ->find();        
            
            if(!$goods || ($goods['is_spec'] && !$item['sku_id']) || (!$goods['is_spec'] &&  $item['num'] > $goods['stock'])  ){
                $title = (!$goods['is_spec'] &&  $item['num'] > $goods['stock']) ?  '【库存不足】' : '【已失效】';
                $item["goods_name"] =  $title. $item["goods_name"];
                $item['goods_thumb'] = get_thumb($item['goods_thumb']); 
                $item['stock'] = $goods ? $goods['stock'] : 0;
                $item['status'] = $item['is_choose'] =  0;  
                $item['is_valid'] = 1;
                //$noList['goodslist'][] = $item;
                continue;
            }             
            if($item['sku_id']){
                $map=[];
                $map[] = ['goods_id','=',$item['goods_id']];
                $map[] = ['sku_id','=',$item['sku_id']];
                $sku = GoodsSku::where($map)->field("stock,member_price,shop_price")->find();    
                if(!$sku || ( $item['num'] > $sku["stock"] )){
                    $title = $item['num'] > $sku["stock"] ?  '【库存不足】' : '【已失效】';
                    $item["goods_name"] =  $title . $item["goods_name"];
                    $item['goods_thumb'] = get_thumb($item['goods_thumb']);   
                    $item['stock'] = $sku ? $sku['stock'] : 0;
                    $item['status']  = $item['is_choose']  =  0;      
                    $item['is_valid'] = 1;
                    //$noList['goodslist'][] = $item;                  
                    continue;
                }
                $item['stock'] = $sku['stock'];
                $item['member_price'] = $sku['member_price'];
                $shop_price = $sku['shop_price'];
            }else{
                $item['stock'] = $goods['stock'];
                $item['member_price'] = $goods['member_price'];
                $shop_price = $goods['shop_price'];
            }      
            $item['shop_price'] = $shop_price;  
            $item['status']  = 1;
            $item['is_valid'] = 0;
            $item["goods_name"] = $goods['name'];  
            $item['goods_thumb'] =  get_thumb($goods['thumb']);  
            
            $item['is_shop_reduce_price'] = 0;//暂时屏蔽
            $item['shop_reduce_price'] = 0;//暂时屏蔽
            $item['is_sale'] = 1;
            $item['is_wholesale'] =  0;//暂时屏蔽
            
            if (!$item['shop_price']) {
                $item['coupon'] = 0;
                continue;
            }
            $money = bcmul($item['shop_price'],$item['num'],2);
            //计算优惠券金额
            $coupon = \app\operation\model\Coupon::view("operation_coupon")
                ->view("operation_coupon_record", false, "operation_coupon_record.cid=operation_coupon.id")
                ->where("operation_coupon_record.status", 1)
                ->where("operation_coupon_record.start_time", "<=", $time)
                ->where("operation_coupon_record.end_time", ">=", $time)
                ->where("operation_coupon_record.user_id", $userid)
                ->where("operation_coupon.min_order_money", "<=", $money)
                ->value("operation_coupon.money");
            $item['coupon'] = $coupon ?: 0;
        }
        return ApiReturn::r(1, $list, lang('购物车列表'));
    }

    /**
     * 获取购物车商品数量
     * @param $data
     * @param $user
     */
    public function get_cart_num($data, $user)
    {
        $count = CartModel::where('user_id', $user['id'])->sum('num');
        return ApiReturn::r(1, $count, lang('购物车商品数量'));
    }

    /*
     * 移入收藏夹
     *
     */
    public function add_collect($data, $user)
    {     
        $cart_ids = explode(',', $data['cart_ids']);
        $list = CartModel::view("goods_cart","id")
                ->view("goods","id as goods_id,name,thumb,shop_price,sales_sum","goods_cart.goods_id = goods.id","left")
                ->where("goods_cart.user_id",$user["id"])
                ->where("goods_cart.id","in",$cart_ids)
                ->fieldRaw("group_concat(goods_cart.id) as ids")
                ->group("goods_cart.goods_id")
                ->select();
        $insert_data =  [];  
        foreach ($list as $cart) {
            $ids = explode(",",$cart['ids']);
            CartModel::where("id","in",$ids)->delete();
            //已失效的商品跳过去
            if(!$cart['goods_id']){
                continue;
            }   
            $check = Collection::where([ 'user_id' => $user['id'], 'type' => 1,'collect_id' => $cart['goods_id'] ])->find();
            if (!$check) {
                $insert_data[$cart['goods_id']] = [
                    'create_time' => time(),
                    'update_time' => time(),
                    'status' => 1,
                    'user_id' => $user['id'],
                    'type' => 1,
                    'collect_title' => $cart['name'],
                    'collect_img' => get_file_url($cart['thumb']),
                    'collect_price' => $cart['shop_price'],
                    'collect_sales' => $cart['sales_sum'],
                    'collect_id' => $cart['goods_id'],
                ];
            }           
        }      
        if(!empty($insert_data)){
            (new Collection())->insertAll($insert_data);
        }    
        return ApiReturn::r(1, [], lang('移入收藏夹成功'));
    }

   
    /**
     * 删除购物车商品
     * 清除购物车失效商品 合并接口
     * @param $data .cart_ids
     * @param $user
     */
    public function remove_goods($data, $user)
    {
        $cart_ids = $data['cart_ids'];
        if(!is_array($cart_ids)){
            $cart_ids = explode(",",$cart_ids);
        }
        $where = [
            ['user_id', '=', $user['id']],
            ['id', 'in', $cart_ids]
        ];
        CartModel::where($where)->delete();
        return ApiReturn::r(1, [], lang('清除成功'));
    }

    /*
     * 修改购物车规格
     *
     */
    public function edit_cart($data, $user)
    {
        $cart_id = $data['cart_id'];
        $sku_id = $data['sku_id'];
        $shop_price = $data['shop_price'];
        $sku_name = $data['sku_name'];
        $update_data = [
            'sku_id' => $sku_id,
            'shop_price' => $shop_price,
            'sku_name' => $sku_name
        ];
        $sku_info = CartModel::where(['id' => $cart_id])->find();
        $has_same_sku = CartModel::where('id', '<>', $cart_id)
            ->where([
                'user_id' => $sku_info['user_id'],
                'goods_id' => $sku_info['goods_id'],
                'sku_id' => $data['sku_id']
            ])
            ->find();
        if ($has_same_sku) {
            CartModel::where(['id' => $cart_id])->delete();
            return ApiReturn::r(2, [], 'ok');
        } else {
            CartModel::where(['id' => $cart_id])->update($update_data);
            return ApiReturn::r(1, [], 'ok');
        }
    }
    
    

    /**
     * 添加或减少购物车商品数量
     * @param $data .sku_id 商品sku
     * @param $data .num 数量，默认为1
     * @edit 晓风<215628355@qq.com> 2021年3月1日15:36:44 优化BUG,改为模型查询
     */
    public function add_cart($data, $user)
    {
        $skuid = $data['sku_id'] ?? 0;
        $userid = $user['id'];
        $goodsid = $data['goods_id'];
        
        if( $data['num'] <= 0){
            return ApiReturn::r(0, '', '数量操作有误');
        } 
        if ($skuid) {
            $goods =  GoodsModel::view("goods","id as goods_id,name as goods_name,thumb,is_spec")
                ->view('goods_sku',"sku_id,key_name as sku_name,shop_price,member_price,stock,spec_img", 'goods_sku.goods_id = goods.id')               
                ->where('goods_sku.sku_id', $skuid)
                ->where("goods.id",$goodsid)
                ->where(['goods.status'=>1,'goods.is_sale'=>1,'goods.is_delete'=>0,'goods.status'=>1])
                ->find();
            $rc = CartModel::field('id,num')->where('user_id', $userid)->where(['goods_id'=>$goodsid,'sku_id'=>$skuid])->find();
        } else {
            $goods = GoodsModel::field('id as goods_id,name as goods_name,thumb,shop_price,member_price,stock,is_spec')
                ->where(['status'=>1,'is_sale'=>1,'is_delete'=>0])
                ->where('id', $goodsid)
                ->find();
            $rc = CartModel::field('id,num')->where('user_id', $userid)->where(['goods_id'=>$goodsid,'sku_id'=>0])->find();
        }        
        if (!$goods) {
            return ApiReturn::r(0, '', '商品已下架');
        }
        //不知道前端怎么回事，瞎搞
        if($goods["is_spec"] && !$skuid){
            return ApiReturn::r(0, '', '请选择规格');
        }
        
        $param = [
            'user_id' => $userid,
            'goods_id' => $goods['goods_id'],
            'sku_id' => $goods['sku_id'] ?? 0,
            'sku_name' => $goods['sku_name'] ?? '',
            'goods_name' => $goods['goods_name'],      
            'shop_price' => $goods['shop_price'],
            'member_price' => $goods['member_price'],
            'goods_thumb' => empty($goods['spec_img']) ? $goods['thumb'] : $goods['spec_img'],
            "num"=> $data['num'],          
        ];
        $stock = $goods['stock'];     
        // 判断是否已加入购物车
        if ($rc) {
            // 检测最大库存
            $param['num'] += $rc['num'];           
            if ($stock < $param['num']) {
                return ApiReturn::r(0, '', '已无多余的库存');
            }
            $rs = CartModel::where('id', $rc['id'])->update(['num'=>$param['num']]);
        } else {
            if ($stock < $param['num']){
                return ApiReturn::r(0, '', '已无多余的库存');
            }
            $rs = CartModel::create($param);
            CartLog::AddCartLog([
                "goods_id" => $goodsid,
                "sku_id" => $skuid,
                "user_id" => $user['user_id'],
                "operation" => "加入购物车",
            ]);
        }
        if ($rs) {
            return ApiReturn::r(1, [], '添加成功');
        } 
        return ApiReturn::r(0, [], '操作失败');    
    }

  
    /**
     * 购物车商品数量操作
     * @author 晓风<215628355@qq.com> 
     * @date 2021年11月5日14:07:46
     */
    public function set_goods($data, $user)
    {
        $cart_id = $data['cart_id'];
        $num = $data['num'];
        $cart = CartModel::get($cart_id);
        if(!$cart){
            return ApiReturn::r(0, '', '购物车已删除');
        }
        if($num <= 0){
           return ApiReturn::r(0, '', '数量参数有误');
        }
  
        // 检测最大库存
        if($cart['sku_id']){
            $stock = (int) GoodsSku::where('sku_id', $cart['sku_id'])->value('stock');
        }else{
            $stock = (int) GoodsModel::where('id', $cart['goods_id'])->value('stock');
        }
        if ( $stock < $num) {
             return ApiReturn::r(0, '', '已无多余的库存');
        }
        $rs = CartModel::where('id', $cart_id)->update(['num' => $num]);
        if (!$rs) {
            return ApiReturn::r(0, [], '操作失败');
        }
        return ApiReturn::r(1, [], '添加成功');
    }
   

    /**
     * 检查商品库存数量
     * @author 晓风<215628355@qq.com>
     * @date 2021年11月5日14:07:46
     */
    public function check_goods_num($data, $user)
    {      
        $cart_ids = explode(",", $data['cart_ids']);
        $list = CartModel::where("user_id",$user["id"])->where("id","in",$cart_ids)->select();   
        foreach ($list as  $cart_detail) {         
            $where = [];
            if ($cart_detail['sku_id'] > 0) {
                $where[] = ['sku_id', '=', $cart_detail['sku_id']];
                $where[] = ['stock', '>=', $cart_detail['num']];
                $detail = GoodsSku::where($where)->find();
            } else {
                $where[] = ['id', '=', $cart_detail['goods_id']];
                $where[] = ['stock', '>=', $cart_detail['num']];
                $detail = GoodsModel::where($where)->find();
            }
            if (!$detail) {
                return ApiReturn::r(0, [], $cart_detail['goods_name'] . lang('库存不足'));
            }    
        }
        return ApiReturn::r(1, [], lang('请求成功'));
    }
}
